<template>
  <div
    class="jp-wrapper"
    :class="{ 'jp-sidebar--fold': sidebarFold, 'jp-sidebar--hide': sidebarHide}" @click="handleClick">
    <template>
     <main-navbar ref="navbar" @showRight="showRight" @OnHandleClick="handleClick"/>
     <main-sidebar v-show="leftMenuList.length >= 1"/>
     <div class="jp-content__wrapper" :style="{ 'min-height': documentClientHeight + 'px' }">
        <main-content/>
      </div>
      <main-right ref="mainRight"/>
    </template>
  </div>
</template>

<script>
  import {clearLoginInfo} from '@/utils'
  import MainNavbar from './layout/_common_top'
  import MainSidebar from './layout/_common_left'
  import MainContent from './layout/_common_center'
  import MainRight from './layout/_common_right'
  import moment from 'moment'
  var unClickTimeCount = 0;
  export default {
    data () {
      return {
        isRightVisible: false,
        websock: null,
        timer: null
      }
    },
    components: {
      MainNavbar,
      MainSidebar,
      MainContent,
      MainRight
    },
    computed: {
      documentClientHeight: {
        get () {
          return this.$store.state.common.documentClientHeight
        },
        set (val) {
          this.$store.commit('common/updateDocumentClientHeight', val)
        }
      },
      sidebarFold: {
        get () {
          return this.$store.state.common.sidebarFold
        }
      },
      sidebarHide: {
        get () {
          return this.leftMenuList.length === 0
        }
      },
      leftMenuList: {
        get () {
          return this.$store.state.common.leftMenuList
        }
      },
      loginOutMinute: {
        get () {
          var loginOutMinute = this.$store.state.config.loginOutMinute;
          if(!loginOutMinute || loginOutMinute == '') {
            return -1;
          }
          return parseInt(loginOutMinute);
        }
      }
    },
    created () {
    },
    mounted () {
      this.getConfig()
      this.resetDocumentClientHeight()
      this.getManagementData()
      this.getIbeacons()
      //this.initWebSocket();

      this.timer = setInterval(()=>{
        unClickTimeCount++;
        if(this.loginOutMinute > 0 && unClickTimeCount > this.loginOutMinute*60) {
          unClickTimeCount = 0;
          this.logoutHandle();
        }
      }, 1000)
    },
    beforeDestroy() {
      if(this.websock) {
        this.websock.close() //离开路由之后断开websocket连接
      }
      if(this.timer) {
        clearInterval(this.timer)
        this.timer = null;
      }
    },
    methods: {
      handleClick() {
        unClickTimeCount = 0;
      },
      logoutHandle () {
          this.$http({
            url: '/sys/logout',
            method: 'get'
          }).then(({data}) => {
            if (data && data.success) {
              clearLoginInfo()
              this.$router.replace({name: 'login'})
            }
          })
      },
      // 重置窗口可视高度
      resetDocumentClientHeight () {
        this.documentClientHeight = document.documentElement['clientHeight']
        window.onresize = () => {
          this.documentClientHeight = document.documentElement['clientHeight']
          if(this.$refs.navbar) {
            this.$refs.navbar.fixTopMenu()
          }
        }
      },
      showRight (flag) {
        this.$refs.mainRight.showRight()
        this.isRightVisible = flag
      },
      getManagementData() {
        this.$http({
          url: '/smis/api/getManagementData',
          method: 'get',
          params: {
          }
        }).then(({ data }) => {
          if (data && data.success) {
            this.updateShopData(data.data)
           }
        })
      },
      updateShopData(data) {
        this.$store.commit('shopdata/updateBuildingList', data.buildingList)
        this.$store.commit('shopdata/updateFloorList', data.floorList)
        this.$store.commit('shopdata/updateMerchantList', data.merchantList)
        this.$store.commit('shopdata/updateElevatorList', data.elevatorList)
        this.$store.commit('shopdata/updateParkSpaceList', data.parkSpaceList)
        this.$store.commit('shopdata/updateUtilitieList', data.utilitieList)
        this.$store.commit('shopdata/updateUtilitieTypeList', data.utilitieTypeList)
        this.$store.commit('shopdata/updateRoomList', data.roomList)
        this.$store.commit('shopdata/updateMeshList', data.meshList)
        this.$store.commit('config/updateProjectName', data.project.name);
      },
      getIbeacons() {
        this.$http({
          url: '/smis/api/getIbeacons',
          method: 'get',
          params: {
          }
        }).then(({ data }) => {
          if (data && data.success) {
            this.$store.commit('shopdata/updateIbeaconsMap', data.data);
            // this.updateShopData(data.data)
           }
        })
      },
      getConfig () {
        // 获取产品name 和 logo
        this.$http.get('/sys/sysConfig/queryById').then(({data}) => {
          if (data.success) {
            this.$store.commit('config/updateProductName', data.config.productName)
            this.$store.commit('config/updateLogo', data.config.logo)
            if (!localStorage.getItem('defaultLayout')) {
              this.$store.commit('config/updateDefaultLayout', data.config.defaultLayout)
            }
            if (!localStorage.getItem('defaultTheme')) {
              this.$store.commit('config/updateDefaultTheme', data.config.defaultTheme)
            }
            this.$store.commit('config/updateConfig', data.config)
          }
        })

        this.$http({
          url: '/smis/config/jfConfig/list',
          method: 'get',
          params: {
            'pageNo': 1,
            'pageSize': 1000,
          }
        }).then(({data}) => {
          if (data && data.success) {
            data.page.list.forEach((config) => {
              if(config["keyStr"] === "languageConfig") {
                this.$store.commit('user/updateLanguages', JSON.parse(config["valueStr"]))
              } else if(config["keyStr"] === "manageConfig") {
                this.$store.commit('config/updateBackParam', JSON.parse(config["valueStr"]))
              } else if(config["keyStr"] === "merchantFileConfig") {
                this.$store.commit('config/updateMerchant', JSON.parse(config["valueStr"]))
              } else if(config["keyStr"] === "merchantTypeFileConfig") {
                this.$store.commit('config/updateMerchantsType', JSON.parse(config["valueStr"]))
              } else if(config["keyStr"] === "utilitieFileConfig") {
                this.$store.commit('config/updateUtilitiesType', JSON.parse(config["valueStr"]))
              } else if(config["keyStr"] === "secretConfig") {
                var secretConfig = JSON.parse(config["valueStr"])
                var time = (new Date(secretConfig["manageForbid"])).getTime()
                var now = (new Date()).getTime()
                if(time-now < 30*86400*1000) {
                  this.$message.error("系统于"+secretConfig["manageForbid"]+"到期，请联系厂家")
                }
              }
            })
          }
        })
      },
      initWebSocket(){ //初始化WebSocket
        console.log("开始连接....")

        var serverUrl = process.env.VUE_APP_SERVER_URL;
        var serverList = serverUrl.split("://");
        var BASE_WS = serverList[serverList.length-1];
        if(!serverUrl.startsWith("http")) {
          BASE_WS = window.document.location.host+BASE_WS
        }
        if(window.document.location.protocol.startsWith("https")) {
          BASE_WS = 'wss://'+BASE_WS
        } else {
          BASE_WS = 'ws://'+BASE_WS
        }
        const wsuri = BASE_WS+"/systemInfoSocketServer";

        console.log(wsuri)
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        console.log("连接成功")
        // let actions = {"test":"12345"};
        // this.websocketsend(JSON.stringify(actions));
      },
      websocketonerror(e){//连接建立失败重连
        console.log("连接失败")
        console.log(e)
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
      var self = this
        const redata = JSON.parse(e.data);
        if(redata["dataType"] === 'loraAlarm') {
          this.$notify({
            title: redata.alarmText,
            type: 'warning',
            duration: 20000,
            onClick: function(){
              // console.log(redata)
              self.$router.push({ path: '/lora/alarm/JfLoraAlarmList', query: { id: redata.id }})
              this.close();
            },
            message: redata.name+'触发了：'+redata.alarmText
          });
          this.$store.commit('shopdata/updateUnreadAlarmCount', redata.totalUnread)
        }
      },
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
      },
    }
  }
</script>
